package com.yibo.user.service.user;

import com.yibo.redis.RedisCommand;
import com.yibo.support.helper.Assert;
import com.yibo.support.inter.Command;
import com.yibo.user.object.YBUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

import static com.yibo.support.constant.MsgConstant.NOT_LOGIN;
import static com.yibo.support.constant.YBConstant.*;

/**
 * 退出登录
 *
 * @author zhanglei
 */
public class LoginOutCommand implements Command<Integer> {

    /**
     * ip
     */
    private String ip;

    /**
     * token
     */
    private String token;


    @Override
    public Integer execute() {
        initIp();
        Assert.notEmpty(NOT_LOGIN,token);

        //清除redis中的登陆信息
        RedisCommand command = getBean(RedisCommand.class);
        YBUser user = command.get(YIBO_USER_REDIS_PREFIX_TOKEN+this.token,YBUser.class);
        if(user != null){
            command.remove(YIBO_USER_REDIS_PREFIX_USER_ID+user.getUserId());
        }
        command.remove(YIBO_USER_REDIS_PREFIX_TOKEN +token);
        command.remove(YIBO_USER_REDIS_PREFIX_IP+ip);

        return 1;
    }

    private void  initIp(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            this.ip =  request.getHeader(CLI_IP)+"";
            this.token = request.getHeader(TOKEN);
        }catch (Exception e){
            //不抛出异常
        }
    }
}
